package com.ala4.oxcafe.boot.aop;

import com.ala4.oxcafe.common.utils.object.ObjectUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 统计UV的AOP 统计访问次数 每个IP每天只记一次
 *
 * @author PING
 * @version 1.0.0
 * @date 2025/8/18 11:10
 */
@Slf4j
@Aspect
@Component
@AllArgsConstructor
public class StatisticsUVAop {

    private final VisitCounterService visitCounterService;

    @Pointcut("@annotation(com.ala4.oxcafe.boot.annotation.StatisticsUV)")
    public void statisticsUV() {

    }

    @After("statisticsUV()")
    public void afterAdvice() {
        log.debug("StatisticsUVAop afterAdvice");

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        if (ObjectUtil.isNotNull(attributes)) {
            // 获取 HttpServletRequest 对象
            HttpServletRequest request = attributes.getRequest();
            visitCounterService.recordVisit(request, VisitCounterService.BIZ_TYPE_VISITOR_COUNT);
        }
    }
}
